package com.adcc.ags.gms.core.interceptor;

import com.adcc.ags.gms.core.entity.SysUser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录认证的拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * Handler执行完成之后调用这个方法
     */
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception exc)
            throws Exception {

    }

    /**
     * Handler执行之后，ModelAndView返回之前调用这个方法
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
    }

    /**
     * Handler执行之前调用这个方法
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
//        //获取请求的URL
        String url = request.getRequestURI();
        //URL:除了login.jsp和登陆可以公开访问的， 其它的URL都进行拦截控制
        if (url.equals("/GMS/login")) {
            return true;
        }
        //通过webjars resources获取的静态文件不进行拦截
//        if (url.contains("webjars")||url.contains("resources")) {
//            return true;
//        }
        //获取Session
        HttpSession session = request.getSession();
        SysUser user = (SysUser) session.getAttribute("user");

        if (user != null) {
            return true;
        } else {
            //不符合条件的，或路径错误的；跳转到登录界面
            response.sendRedirect("/GMS/");
            return false;
        }

    }

}